package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 *订单定时任务类
 */
@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 订单超时处理，自动取消订单
     *
     */
    //每分钟执行一次
    @Scheduled(cron = "0 0/1 * * * ?")
    public void processTimeoutOrder(){
        log.info("订单超时处理，自动取消订单...");

        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        //sql:SELECT * FROM orders WHERE status = 1 AND order_time < time
        List<Orders> orders = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT,time);

        if(orders != null && orders.size() > 0){
            for(Orders order : orders){
                order.setStatus(Orders.CANCELLED);
                order.setCancelReason("订单超时，自动取消");
                order.setCancelTime(LocalDateTime.now());
                //sql:UPDATE orders SET status = ?,cancel_reason = ?,cancel_time = ? WHERE id = ?
                orderMapper.update(order);
            }
        }
    }

    /**
     * 订单派送成功后，自动确认订单
     *
     */
    //每天凌晨1点执行一次
    @Scheduled(cron = "0 0 1 * * ?")
    public void processCompleteOrder(){
        log.info("订单派送成功后，自动确认订单...");

        LocalDateTime time = LocalDateTime.now().plusMinutes(-60);
        //sql:SELECT * FROM orders WHERE status = 5 AND order_time < time
        List<Orders> orders = orderMapper.getByStatusAndOrderTimeLT(Orders.COMPLETED,time);

        if(orders != null && orders.size() > 0){
            for(Orders order : orders){
                order.setStatus(Orders.COMPLETED);
//                order.setDeliveryTime(LocalDateTime.now());
                //sql:UPDATE orders SET status = ?,delivery_time = ? WHERE id = ?
                orderMapper.update(order);
            }
        }
    }
}
